import NotFound from "@/components/NotFound/index.vue";
import { getFromLocalStorage } from "@/utils/store-data";
import Login from "@/views/Login/index.vue";
import Auth from "@/views/Manager/Auth.vue";
import Charts from "@/views/Manager/Charts.vue";
import Home from "@/views/Manager/Home.vue";
import Manager from '@/views/Manager/index.vue';
import Logs from "@/views/Manager/Logs.vue";
import News from "@/views/Manager/News.vue";
import NewsDetail from "@/views/Manager/NewsDetail.vue";
import Notice from "@/views/Manager/Notice.vue";
import Orders from "@/views/Manager/Orders.vue";
import User from "@/views/Manager/User.vue";
import Register from "@/views/Register/index.vue";
import Test from "@/views/test/index.vue";
import { createRouter, createWebHistory } from "vue-router";

const routes = [
  {
    path: "/",
    component: Manager,
    name: 'Manager',
    redirect: '/home',
    children: [
      { path: "home"  , name: "Home"  , meta: { name: "系统首页" },     component: Home  },
      { path: "403"   , name: "Auth"  , meta: { name: "无权限"   },     component: Auth  },
      { path: "user"  , name: "User"  , meta: { name: "用户信息" },     component: User  },
      { path: "news"  , name: "News"  , meta: { name: "新闻信息" },     component: News  },
      { path: "notice", name: "Notice", meta: { name: "系统公告" },     component: Notice},
      { path: "logs"  , name: "Logs"  , meta: { name: "系统日志" },     component: Logs  },
      { path: "charts", name: "Charts", meta: { name: "数据统计" },     component: Charts},
      { path: "orders", name: "Orders", meta: { name: "订单管理" },     component: Orders},
      { path: "newsDetail"  , name: "NewsDetail"  , meta: { name: "新闻详情" },     component: NewsDetail  },
    ],
  },
  { path: '/login',                 name: 'Login',                meta: {name: 'Login'   },              component: Login   },
  { path: '/register',              name: 'Register',             meta: {name: 'Register'},              component: Register},
  { path: '/test',                  name: 'Test',                 meta: {name: 'Test'    },              component: Test    },
  { path: '/notfound',              name: 'NotFound',             meta: {name: 'NotFound'},              component: NotFound},
  { path: '/:pathMatch(.*)',        name: 'NotFound',             meta: {name: 'NotFound'},              component: NotFound},
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

router.beforeEach((to, from, next) => {
  const adminPaths  = ['/user', '/logs']
  const currentUser = getFromLocalStorage("current-user") || '{}'

  if(currentUser.role !== 'ADMIN' && adminPaths.includes(to.path)){
    // 当前登录的用户不是管理员 且 要访问的路径是管理员才能访问的 => 403 无权限
    next('/403')
  }else{
    next()
  }
})
export default router;
